import pyaudio
import datetime
import wave
import numpy as np
import matplotlib.pyplot as plt
from audio import (
    save_audio,
    calculate_threshold,
    count_hits,
    plot_waveform,
    get_user_choice,
    rate,
    chunk_size,
    record_seconds,
    threshold_multiplier,
    buffer_size,
)
from game import (
    get_computer_choice,
    determine_winner,
)

def record_audio(stream, filename):
    frames = []
    for i in range(int(rate / chunk_size * record_seconds)):
        data = stream.read(chunk_size)
        frames.append(data)

    save_audio(filename, frames)
    print(f"音频已保存为：{filename}")

def play_game_loop(stream):
    print("欢迎来到剪刀石头布游戏！")
    input("按回车键开始录制音频...")
    print("录音开始...")

    while True:
        current_time = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
        filename = f"audio_{current_time}.wav"

        record_audio(stream, filename)

        with wave.open(filename, "rb") as wf:
            num_frames = wf.getnframes()
            audio_data = np.frombuffer(wf.readframes(num_frames), dtype=np.int16)

        hit_threshold = calculate_threshold(audio_data)
        hit_count = count_hits(audio_data, hit_threshold)
        print(f"HIT次数：{hit_count}")

        if hit_count == 0:
            user_choice = get_user_choice()
        else:
            user_choice = ['剪刀', '石头', '布'][hit_count - 1]

        computer_choice = get_computer_choice()
        print("用户选择:", user_choice)
        print("电脑选择:", computer_choice)
        winner = determine_winner(user_choice, computer_choice)
        print("结果:", winner)

        plot_waveform(audio_data)

        user_input = input("按回车键继续录制音频，输入其他字符退出程序：")
        if user_input != "":
            break

        print("录音开始...")

    print("录音结束...")

def main():
    p = pyaudio.PyAudio()
    stream = p.open(
        format=pyaudio.paInt16,
        channels=1,
        rate=rate,
        frames_per_buffer=chunk_size,
        input=True,
    )

    play_game_loop(stream)

    stream.stop_stream()
    stream.close()
    p.terminate()

if __name__ == "__main__":
    main()
